/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package network.packets;

import datamodel.Order;
import utils.StringUtils;
import utils.Utils;

/**
 *
 * @author Kvest
 */
public class OrdersListResponce extends Packet
{
    private Order[] orders;
    
    public OrdersListResponce(byte[] data)
    {
        super(ORDERS_LIST_RESPONCE, data);
    }
    
    protected void parse(byte[] data) 
    {
        int offset = 2;
        
        //Размер массива районов
        byte[] tmp = new byte[4];
        System.arraycopy(data, offset, tmp, 0, tmp.length);
        offset += tmp.length;
        int size = Utils.byteToInt(tmp);
        
        orders = new Order[size];
     
        //Парсим заявки
        for (int i = 0; i < size; ++i)
        {
            //id
            tmp = new byte[4];
            System.arraycopy(data, offset, tmp, 0, tmp.length);
            offset += tmp.length;
            
            orders[i] = new Order(Utils.byteToInt(tmp));
            
            //PreviewText
            System.arraycopy(data, offset, tmp, 0, tmp.length);
            offset += tmp.length;        
            tmp = new byte[Utils.byteToInt(tmp)];
            System.arraycopy(data, offset, tmp, 0, tmp.length);
            offset += tmp.length;
            orders[i].setPreviewText(StringUtils.bytesToStr(tmp));        
            
            //fullText
            tmp = new byte[4];
            System.arraycopy(data, offset, tmp, 0, tmp.length);
            offset += tmp.length;      
            tmp = new byte[Utils.byteToInt(tmp)];
            System.arraycopy(data, offset, tmp, 0, tmp.length);
            offset += tmp.length;
            orders[i].setFullText(StringUtils.bytesToStr(tmp));
        }
        
        System.gc();
    }
    
    public void print() 
    {
        String str = "OrdersListResponce[\n";
        for (int i = 0; i < orders.length; ++i)
        {
            str += orders[i].getId() + " {" + orders[i].getPreviewText() + "} { " + orders[i].getFullText() + "}\n";
        }
        System.out.println(str + "]");
    }

    public int getOrdersCount()
    {
        return orders.length;
    }

    public Order getOrder(int index)
    {
        return orders[index];
    }
}
